package noticeutil;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.utils.module.R;
import com.utils.module.ScreenUtils;

/**
 * Created by Administrator on 2016/8/19.
 */
public class NoticeHelper {

    private PopupWindow popupwindow;
    private Context mContext;
    private View root ;
    private TextView customView ;

    private NoticeHelper(){};
    private static NoticeHelper instance = new NoticeHelper() ;
    public static NoticeHelper getInstance(){
        return instance ;
    }

    public void init(Context context,View root){
        mContext = context ;
        this.root = root ;
        initmPopupWindowView();
    }

    public void initmPopupWindowView() {
        // // 获取自定义布局文件pop.xml的视图
        customView = (TextView) View.inflate(mContext, R.layout.notice, null);
        // 创建PopupWindow实例,200,150分别是宽度和高度
        popupwindow = new PopupWindow(customView, ScreenUtils.getScreenWidth(mContext), 120);
        // 设置动画效果 [R.style.AnimationFade 是自己事先定义好的]
        popupwindow.setAnimationStyle(R.style.AnimationFade);
        // 自定义view添加触摸事件
//        customView.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (popupwindow != null && popupwindow.isShowing()) {
//                    popupwindow.dismiss();
//                    popupwindow = null;
//                }
//                return false;
//            }
//        });
    }

    Handler handler = new Handler(){
        @Override
        public void dispatchMessage(Message msg) {
            popupwindow.dismiss();
        }
    };

    public void showNotice(String text) {
        if ( popupwindow.isShowing() ){
            popupwindow.dismiss();
            handler.removeMessages(0);
        }
        popupwindow.showAsDropDown(root, 0, 0);
        customView.setText(text);
        handler.sendEmptyMessageDelayed(0,2500);
    }

    public void dismiss() {
        handler.removeMessages(0);
        if (popupwindow!=null)
            popupwindow.dismiss();
    }

}
